import { Injectable } from '@angular/core';

import * as echarts from 'echarts'
import * as $ from 'jquery';

@Injectable()
export class EChartsService {
    constructor() { }

    getChart(referenceVariables: any): any {
        let myChart = echarts.init(referenceVariables);

        $(window).bind('resize', myChart.resize);

        return myChart;
    }

    setOptions(myChart: any, option: any): void {
        myChart.hideLoading();
        myChart.clear();
        myChart.setOption(option);
    }

    // 有时候图表会放在多个标签页里，那些初始隐藏的标签在初始化图表的时候因为获取不到容器的实际高宽，可能会绘制失败，
    // 因此在切换到该标签页时需要手动调用 resize 方法获取正确的高宽并且刷新画布
    resize(myChart: any): void {
        myChart.resize();
    }

    disposeChart(myChart: any): void {
        if (!myChart.isDisposed()) {
            $(window).unbind('resize', myChart.resize);

            myChart.dispose();
        }
    }
}
